import NavBar from '@/components/NavBar';
import { useAppDispatch, useAppSelector } from '@/store';
import {
  getUserProfileAction,
  updatePhotoAction,
  updateProfileAction,
} from '@/store/action/user';
import { Dialog, List, Popup } from 'antd-mobile';
import { useEffect, useRef, useState } from 'react';
import styles from './index.module.scss';
import { Toast } from 'antd-mobile';
import { IUserProfile } from '@/store/reducer/user';
import Input from '@/components/Input';
import TextArea from '@/components/TextArea';
import { DatePicker } from 'antd-mobile';
import dayjs from 'dayjs';
import { removeAuth } from '@/utils/storage';
import history from '@/utils/history';

type EditType = 'photo' | 'gender' | 'name' | 'intro';

export default function ProfileEdit() {
  const dispatch = useAppDispatch();
  useEffect(() => {
    dispatch(getUserProfileAction());
  }, [dispatch]);
  const { userProfile } = useAppSelector((state) => state.user);

  const [editType, setEditType] = useState('' as EditType);
  const [visible, setVisible] = useState(false);
  const [rightVisible, setRightVisible] = useState(false);
  const [birthVisible, setBirthVisible] = useState(false);

  const iptRef = useRef<HTMLInputElement>(null);
  const handleShowFile = () => iptRef.current?.click();

  const [name, setName] = useState('');
  const [intro, setIntro] = useState('');

  useEffect(() => {
    setName(userProfile.name);
    setIntro(userProfile.intro || '');
  }, [userProfile]);

  const handleUpdatePhoto = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const formData = new FormData();
    const files = e.target.files;
    if (files?.length) {
      formData.append('photo', files[0]);
      await dispatch(updatePhotoAction(formData));

      dispatch(getUserProfileAction());
      Toast.show('上传成功');
      setVisible(false);
    }
  };

  const handleUpdateProfile = async (data: Partial<IUserProfile>) => {
    await dispatch(updateProfileAction(data));

    dispatch(getUserProfileAction());
    Toast.show({ icon: 'success', content: '更新成功' });
    setVisible(false);
    setRightVisible(false);
    setBirthVisible(false);
  };

  const renderPhotoAndGender = () => {
    if (editType === 'photo') {
      return (
        <>
          <div className="list-item" onClick={handleShowFile}>
            拍照
          </div>
          <div className="list-item" onClick={handleShowFile}>
            本地选择
          </div>
          <div className="list-item" onClick={() => setVisible(false)}>
            取消
          </div>
        </>
      );
    }

    if (editType === 'gender') {
      return (
        <>
          <div
            className="list-item"
            onClick={() => handleUpdateProfile({ gender: 0 })}
          >
            男
          </div>
          <div
            className="list-item"
            onClick={() => handleUpdateProfile({ gender: 1 })}
          >
            女
          </div>
          <div className="list-item" onClick={() => setVisible(false)}>
            取消
          </div>
        </>
      );
    }
  };

  const showPopup = (type: EditType) => {
    if (type === 'photo' || type === 'gender') setVisible(true);
    if (type === 'name' || type === 'intro') setRightVisible(true);
    setEditType(type);
  };

  const handleBack = () => {
    setRightVisible(false);
    setName(userProfile.name);
    setIntro(userProfile.intro);
  };

  const renderNameAndIntro = () => {
    const updateParams = {
      [editType]: editType === 'name' ? name : intro,
    };
    return (
      <>
        <NavBar
          onBack={handleBack}
          right={
            <span
              onClick={() => handleUpdateProfile(updateParams)}
              className="submit-btn"
            >
              提交
            </span>
          }
        >
          编辑用户信息
        </NavBar>
        <div className="edit-content">
          {editType === 'name' && (
            <Input
              autoFocus
              value={name}
              onChange={(e) => setName(e.target.value)}
              className="edit-input"
            />
          )}
          {editType === 'intro' && (
            <TextArea
              onChange={(e) => setIntro(e.target.value)}
              value={intro}
            />
          )}
        </div>
      </>
    );
  };

  const handleLoginOut = () => {
    Dialog.confirm({
      content: '确认退出吗？',
      title: '温馨提示',
      onConfirm() {
        removeAuth();
        history.push('/');
        Toast.show({ icon: 'success', content: '退出成功' });
      },
    });
  };

  return (
    <div className={styles.root}>
      <div className="content">
        <NavBar>个人资料</NavBar>

        <div className="wrapper">
          <List className="profile-list">
            <List.Item
              arrow
              extra={<img className="avatar" src={userProfile.photo} alt="" />}
              onClick={() => showPopup('photo')}
            >
              头像
            </List.Item>
            <List.Item
              onClick={() => showPopup('name')}
              arrow
              extra={userProfile.name}
            >
              昵称
            </List.Item>

            <List.Item
              onClick={() => showPopup('intro')}
              arrow
              extra={<span className="intro">{userProfile.intro}</span>}
            >
              简介
            </List.Item>

            <List.Item
              onClick={() => showPopup('gender')}
              arrow
              extra={userProfile.gender === 0 ? '男' : '女'}
            >
              性别
            </List.Item>
            <List.Item
              onClick={() => setBirthVisible(true)}
              arrow
              extra={userProfile.birthday?.slice(0, 10)}
            >
              生日
            </List.Item>
          </List>

          <input
            onChange={handleUpdatePhoto}
            ref={iptRef}
            className="avatar-upload"
            type="file"
          />
        </div>

        <div className="logout">
          <button className="btn" onClick={handleLoginOut}>
            退出登录
          </button>
        </div>
      </div>
      <Popup
        visible={visible}
        position="bottom"
        bodyClassName="popup-bottom-list"
      >
        {renderPhotoAndGender()}
      </Popup>
      <Popup
        destroyOnClose
        visible={rightVisible}
        position="right"
        bodyClassName="popup-right"
      >
        {renderNameAndIntro()}
      </Popup>
      <DatePicker
        min={new Date('1900-01-01')}
        max={new Date()}
        title="选择生日"
        visible={birthVisible}
        value={new Date(userProfile.birthday?.slice(0, 10))}
        onCancel={() => setBirthVisible(false)}
        onConfirm={(val) => {
          handleUpdateProfile({ birthday: dayjs(val).format('YYYY-MM-DD') });
        }}
      />
    </div>
  );
}
